import { message } from 'antd';
import { query2search } from './common';

type ReqConfig = {
  url?: string;
  method?: 'get' | 'post';
  params?: Record<string, any>;
  headers?: Record<string, string>;
  data?: any;
  showMsg?: boolean;
};
function req<T>({
  url = '',
  method = 'get',
  params = {},
  data = null,
  headers = {},
  showMsg = true,
}: ReqConfig): Promise<T> {
  return new Promise((resolve, reject) => {
    const search = query2search(params);

    if (search) {
      url += url.indexOf('?') == -1 ? '?' + search : '&' + search;
    }

    // headers['token'] = localStorage.getItem('token') || ''
    const xhr = new XMLHttpRequest();
    xhr.open(method, url, true);
    if (!headers['Content-Type']) {
      headers['Content-Type'] = 'application/json;charset=UTF-8';
    }

    for (const key in headers) {
      // xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencode');
      xhr.setRequestHeader(key, headers[key]);
    }
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status >= 200 && xhr.status < 300) {
          const data = JSON.parse(xhr.responseText);
          resolve(data);
        } else {
          const res = JSON.parse(xhr.responseText);
          if (res.message && showMsg) {
            message.error(res.message);
          }
          // if (res.code === '1001') {
          //   window.location.href = res.data
          // }
          reject(res);
        }
      }
    };
    xhr.onerror = function () {
      reject(new Error('Network Error'));
    };
    xhr.send(typeof data == 'object' && data !== null ? JSON.stringify(data) : data);
  });
}
const get = <T = any>(url: string, params: ReqConfig['params'] = {}, config: ReqConfig = {}) => {
  return req<T>({ url, method: 'get', params, ...config });
};
const post = <T = any>(url: string, data: ReqConfig['data'] = {}, config: ReqConfig = {}) => {
  return req<T>({ url, method: 'post', data, ...config });
};
export default {
  get,
  post,
};
